package webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.person;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllSeminar;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllSeminarsImplToSeminarLinkPanel;
import webEquipeRechercheGwt.client.entityMirror.SeminarMirror;
import webEquipeRechercheGwt.client.entityShowingPanel.PersonPanel;
import webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.ToSeminarLinkCreationPanel;
import webEquipeRechercheGwt.client.handler.creation.link.person.ClickHandlerPersonToSeminarLink;
import webEquipeRechercheGwt.client.services.SeminarService;
import webEquipeRechercheGwt.client.services.SeminarServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class PersonToSeminarLinkCreationPanel extends HorizontalPanel implements
		ToSeminarLinkCreationPanel {

	private PersonPanel origine;
	private List<SeminarMirror> seminars;
	private ListBox listBox;
	private Button validation;
	
	public PersonToSeminarLinkCreationPanel(PersonPanel origine){
		super();
		this.origine = origine;
		seminars = new ArrayList<SeminarMirror>();
		listBox = new ListBox();
		listBox.setVisibleItemCount(1);
		validation = new Button("Create link");
		validation.addClickHandler(new ClickHandlerPersonToSeminarLink(seminars, listBox, origine.getMirror(), origine.getMainPanel()));
	}
	
	private void loadAllPersons(){
		SeminarServiceAsync service = GWT.create(SeminarService.class);
		AsyncCallback<Collection<SeminarMirror>> callback = new CallBackGetAllSeminar(new CommandGetAllSeminarsImplToSeminarLinkPanel(this));
		service.getSeminars(callback);
	}
	
	public void setSeminars(Collection<SeminarMirror> result){
		seminars.clear();
		seminars.addAll(result);
		seminars.removeAll(origine.getMirror().getSeminars());
		updateSelection();
	}
	
	private void updateSelection(){
		listBox.clear();
		for(SeminarMirror s : seminars){
			listBox.addItem(s.getTitle());
		}
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		add(listBox);
		add(validation);
		loadAllPersons();
	}

}
